package com.aboo.util;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactoryUtil {
	
	private static Logger log = Logger.getLogger(HibernateSessionFactoryUtil.class);
	private static SessionFactory sessionFactory;
	
	static {
		try {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
	}
	
	private static final ThreadLocal localSession = new ThreadLocal();
	private static final ThreadLocal localTransaction = new ThreadLocal();
	
	private static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	private static Session openSession() {
		return getSessionFactory().openSession();
	}
	
	public static void closeSession() {
		Session session = (Session) localSession.get();
		
		try {
			localSession.set(null);
			if (session != null && session.isOpen()) {
				session.flush();
				session.close();
			}
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		
	}
	
	public static Session currentSession() {
		Session session = (Session) localSession.get();
		
		try {
			if (session == null || !session.isOpen()) {
				session = openSession();
				localSession.set(session);
			}
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		
		return session;
	}
	
	public static void beiginTransaction() {
		Transaction transaction = (Transaction) localTransaction.get();
		try {
			if (transaction == null) {
				transaction = currentSession().beginTransaction();
				localTransaction.set(transaction);
			}
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
	}
	
	public static void commitTransaction() {
		Transaction transaction = (Transaction) localTransaction.get();
		try {
			if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) {
				transaction.commit();
				localTransaction.set(null);
			}
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
	}
	
	public static void rollbackTransaction() {
		Transaction transaction = (Transaction) localTransaction.get();
		try {
			if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) {
				transaction.rollback();
				localTransaction.set(null);
			}
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
	}

}
